package com.oa.android.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.oa.android.R;
import com.oa.android.adapter.TxlAdapter;
import com.oa.android.entry.Emil;
import com.oa.android.entry.Txl;
import com.oa.android.utils.UConstants;
import com.oa.android.utils.Util;
import com.oa.android.view.XListView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;


/**
 * 通讯录
 *
 * @author -zouqh
 */
public class TxlActivity extends Activity implements OnClickListener, XListView.IXListViewListener {

    private ImageView close;
    private TextView title, add;
    private int type;
    private List<Txl> txlList;
    private TxlAdapter adapter;
    private XListView listView;
    ProgressDialog dialog;
    private int page = 1;
    private int pageSize = 12;
    private int allPage = 0;
    private String keyword = "";
    private Dialog Jdialog;
    public static TxlActivity activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.txl_activity);
        activity=this;
        close = (ImageView) findViewById(R.id.close);
        title = (TextView) findViewById(R.id.title_text);
        add = (TextView) findViewById(R.id.ritgh_text);
        listView = (XListView) findViewById(R.id.listView);
        add.setText("添加");

        type = Integer.parseInt(getIntent().getStringExtra("type"));
        if (type == 1) {
            title.setText("个人通讯录");
            add.setVisibility(View.VISIBLE);
        } else if (type == 3) {
            title.setText("内部通讯录");
            add.setVisibility(View.GONE);
        } else if (type == 2) {
            add.setVisibility(View.GONE);
            title.setText("共享通讯录");
        }
        listView.setPullLoadEnable(true);// 向上滑动加载更多开启
        listView.setPullRefreshEnable(true);
        listView.setXListViewListener(this);
        listView.setFooterName("", false);
        close.setOnClickListener(this);
        add.setOnClickListener(this);
        txlList = new ArrayList<>();

        adapter = new TxlAdapter(this, txlList);
        listView.setAdapter(adapter);
        getDate(keyword, type);
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Log.i("position----------",""+position);
                if(type==1){
                    pointDialog("确定删除吗？",position-1);
                }

                return true;
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent =new Intent(TxlActivity.this,EditTxlActivity.class);
                Bundle bundle=new Bundle();
                bundle.putSerializable("txl",txlList.get(position-1));
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        Intent intent;
        switch (v.getId()) {
            case R.id.close:
                finish();
                break;

            case R.id.ritgh_text:
                intent=new Intent(this,AddTxlActivity.class);
                intent.putExtra("type",type+"");
                startActivityForResult(intent,1);
//                startActivity(intent);
                break;

            default:
                break;
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (page < allPage) {
                        page++;
                        getDate(keyword, type);
                    } else {
                        listView.setFooterName("", false);
                    }
                    break;

            }

        }
    };

    /**
     * 提示
     */
    private void pointDialog(String str, final int p) {
        LayoutInflater inflaterDl = LayoutInflater.from(this);
        View layout = inflaterDl.inflate(R.layout.exti_dialog,
                null);
        // 对话框
        Jdialog = new Dialog(this);
        Jdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        Jdialog.show();

        Jdialog.setContentView(layout);
        TextView sure = (TextView) layout.findViewById(R.id.sureExti);
        TextView cancle = (TextView) layout.findViewById(R.id.cancleExti);
        TextView dialogTitle = (TextView) layout.findViewById(R.id.dialogTitle);
        dialogTitle.setText(str);
        sure.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
//				ContextUtil.getInstance().finishApp();
                Jdialog.cancel();
                eleteEmil(p);


            }
        });
        cancle.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Jdialog.dismiss();
            }
        });

    }

    //获取通讯录列表
    private void getDate(String emilsTitle, int type) {
        dialog = ProgressDialog.show(this, null, "加载中...", true, false);
        RequestParams params = new RequestParams(UConstants.GET_TXL_LIST);
        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("XM", emilsTitle);
        params.addBodyParameter("EmpId", UConstants.EmpId);
        params.addBodyParameter("LX", type + "");
        params.addBodyParameter("page", page + "");
        params.addBodyParameter("rows", pageSize + "");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (dowmUp){
                    onLoad();
                }
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        allPage = Integer.parseInt(object.getString("total"));
                        allPage = (int) Math.ceil((double) allPage / pageSize);
                        boolean success = object.getBoolean("success");
//                        String msg = object.getString("msg");
                        if (success) {
                            Gson gson = new Gson();
                            Type lt = new TypeToken<List<Txl>>() {
                            }.getType();
                            List<Txl> list = gson.fromJson(object.getString("rows").toString(), lt);
//                            getJson(object.getString("rows").toString());
                            if (list != null && list.size() > 0) {
//								adapter = new CurstorAdapter(OlneSelectActivity.this, crutorJluList);
//								listView.setAdapter(adapter);
                                txlList.addAll(list);
                                adapter.notifyDataSetChanged();
                                if (page == allPage) {
                                    listView.setFooterName("", false);
                                } else if (page <= allPage) {
                                    listView.setFooterVisibility(true);
                                }

                            } else {
                                Toast.makeText(x.app(), "暂无通讯录！", Toast.LENGTH_LONG).show();
                            }

                        } else {
                            Toast.makeText(x.app(), "暂无通讯录！", Toast.LENGTH_LONG).show();
                        }
//                        Toast.makeText(x.app(), msg, Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                dialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "获取数据失败！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    //删除邮件
    private void eleteEmil(final int positon) {
        dialog = ProgressDialog.show(this, null, "加载中...", true, false);
        RequestParams params = new RequestParams(UConstants.DELETE_TXL);
        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("EmpId", UConstants.EmpId);
        params.addBodyParameter("ID", txlList.get(positon).getID());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);

                        boolean success = object.getBoolean("success");
//
                        if (success) {
                            txlList.remove(positon);
                            adapter.notifyDataSetChanged();
                            Toast.makeText(x.app(), "删除成功！", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(x.app(), "删除失败！", Toast.LENGTH_LONG).show();
                        }
//
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                dialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "获取数据失败！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    boolean dowmUp;
    @Override
    public void onRefresh() {
        dowmUp=true;
        fish();

    }

    @Override
    public void onLoadMore() {
        handler.sendEmptyMessage(1);
        onLoad();


    }

    private void onLoad() {
        listView.stopRefresh();
        listView.stopLoadMore();
        listView.setRefreshTime("刚刚");
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1){
            if (resultCode==RESULT_OK){
                if (data!=null){
                    txlList.clear();
                    page=1;
                    adapter.notifyDataSetChanged();
                    getDate(keyword, type);
                }
            }
        }
    }


    /**
     * 编辑完成刷新
     */
    public void fish(){
        page=1;
        txlList.clear();
        adapter.notifyDataSetChanged();
        getDate(keyword, type);
        adapter.notifyDataSetChanged();

    }
}
